package com.user.manage.interceptor;

import com.user.manage.entity.LoginToken;
import com.user.manage.entity.model.UserTokenInfo;
import com.user.manage.service.IUserService;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Component
@Slf4j
public class LoginInterceptor implements org.springframework.web.servlet.HandlerInterceptor {

    @Resource
    IUserService userService;
    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    private String[] excludePath = {"/login", "/register", "/login.html", "/register.html", "/register_success", "/captcha"};

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String servletPath = request.getServletPath();

        for (String path : excludePath) {
            if (antPathMatcher.match(path, servletPath)) {
                log.info("请求路径：{}，无需拦截", servletPath);
                return true;
            }
        }

        String loginToken = "";
        Cookie[] cookies = request.getCookies();

        if (cookies == null) {
            log.info("请求路径：{}，未登录", servletPath);
            response.sendRedirect("/login.html?not_login");
            return false;
        }

        for (Cookie cookie : cookies) {
            if (LoginToken.TOKEN_HEADER.equals(cookie.getName())) {
                loginToken = cookie.getValue();
            }
        }

        if (!StringUtils.hasText(loginToken)) {
            log.info("请求路径：{}，未登录", servletPath);
            response.sendRedirect("/login.html?not_login");
            return false;
        }

        //根据loginToken获取用户信息
        UserTokenInfo userTokenInfo = userService.getUserTokenInfo(loginToken);

        request.setAttribute(UserTokenInfo.TOKEN_INFO_KEY, userTokenInfo);

        return true;
    }
}
